package queue;

import java.util.Arrays;

/**
 * 循环队列的实现类
 * Created by zhaoxin on 2018/7/15.
 */
public class LoopQueue<E> implements Queue<E>{

    private E [] data;
    private int front;
    private int tail;
    private int size;

    public LoopQueue(int capacity){
        // 因为循环队列，在满时会浪费一个元素空间的大小。
        data = (E[]) new Object[capacity + 1];
        front = 0;
        tail = 0;
        size = 0;
    }

    public LoopQueue(){
        this(10);
    }

    /**
     * 整理数组容量
     * @param newCapacity
     */
    private void resize(int newCapacity){
        E [] newData = (E[]) new Object[newCapacity];
        // 将原有数组中的元素移入新组建数组
        for (int i = 0; i < size; i++) {
            newData[i] = data[(i + front) % data.length];
        }
        // 维护循环队列中的front和tail
        front = 0;
        tail = size;
        data = newData;
    }

    /**
     * 入队
     * @param e
     */
    @Override
    public void enqueue(E e) {
        // 判断数组是否已满
        if (front == ((tail + 1) % data.length)){
            resize((data.length * 2) + 1);
        }
        data[tail] = e;
        // 移动tail位置
        tail = (tail + 1) % data.length;
        size++;
    }


    /**
     * 出队
     * @return
     */
    @Override
    public E dequeue() {
        // 判断数组是否为空
        if(front == tail){
            throw new IllegalArgumentException("出队操作中，数组不能为空！");
        }
        E element = data[front];
        data[front] = null;
        // 维护front
        front = (front + 1) % data.length;
        size--;

        // 判断数组缩容的条件
        if (size == data.length / 4 && data.length / 2 != 0){
            resize(data.length / 2);
        }
        return element;
    }

    @Override
    public E getFront() {
        if (front == tail){
            throw new IllegalArgumentException("队列数组不能为空！");
        }
        return data[front];
    }

    @Override
    public boolean isEmpty() {
        return front == tail;
    }

    @Override
    public int getSize() {
        return size;
    }

    /**
     * 获取循环队列容量
     * @return
     */
    public int getCapacity(){
        return data.length - 1;
    }

    @Override
    public String toString() {
        return "LoopQueue{" +
                "data=" + Arrays.toString(data) +
                ", front=" + front +
                ", tail=" + tail +
                ", size=" + size +
                '}';
    }

    public static void main(String[] args) {
        LoopQueue<Integer> queue = new LoopQueue<>();

        for (int i = 0; i < 10; i++) {
            queue.enqueue(i);
            System.out.println(queue);
            if (i % 3 == 2) {
                queue.dequeue();
                System.out.println(queue);
            }
        }

        System.out.println(queue);
    }

}
